package MyApp::Workflow::Action::CreatCompany;

use strict;
use base qw( Workflow::Action );
use Workflow::Exception qw( persist_error );
use Workflow::Factory qw( FACTORY );


sub execute {
	my ($self,$wf) = @_;
	my @fileds = qw(title current_user company_id company_name company_address company_tel sbu_id operation);
	my $context = $wf->context;

	#foreach my $field (@fileds) {
	#	$self->param($field,$context->param($field));
	#}

	my $db = $context->param('db');
	my ($issue_id);

	my $array = $db->query('select number from daiban where workflow_id=? and workflow_type=1',$wf->id)->array;

	#获取流程审批人
	my $agree_user = $db->query('select agree_user from flow_manager where creator=?',$context->param('current_user'))->array->[0];

	if(!$array->[0]){#如果是新建的申请单

		#创建待办记录
		$db->query('insert into daiban (workflow_id,workflow_type,item,agree_user,creator,is_finish) values (?,1,?,?,?,0)',$wf->id,$context->param('title'),$context->param('current_user'),$context->param('current_user'));
		
	}else {#如果是驳回的申请单
        
		#更新下一节点审批人
		$db->query('update daiban set agree_user=?,item=? where workflow_id=? and workflow_type=1',$context->param('current_user'),$context->param('title'),$wf->id);

		#删除原有公司信息申请单
		$db->query('delete from company_application where issue_id=?',$array->[0]);
	}

	#获取待办序列号
	$issue_id = $db->query('select number from daiban where workflow_id=? AND workflow_type=1',$wf->id)->array->[0];

	#创建公司申请单信息
	my $hashes = $context->param('company_infos');

	eval {
		my $tx = $db->begin;
		foreach my $hash (@$hashes) {
			$db->query('insert into company_application (issue_id,id,name,address,tel,sbu,operation,role) values (?,?,?,?,?,?,?,?)',$issue_id,$hash->{id},$hash->{name},$hash->{address},$hash->{tel},$hash->{sbu},$hash->{operation},$hash->{role});
		}
		$db->query('update daiban set agree_user=? where workflow_id=? and workflow_type=1',$agree_user,$wf->id);
		$tx->commit;
	};
	print $@ if $@;

	$wf->add_history(
		Workflow::History->new(
			{
				action => '提交',
				description => sprintf("创建信息申请单"),
				user => $context->param('current_user'),
                                time_zone => 'local'
			}
		)
	);


}

1;
